<template>
  <div>
    <!--  CMS-SAP资金余额对账表 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        columnsRef="qjhcms-sapFundBalanceStatement"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :cellstyles="cellstyles"
        :onRowSelectChange="selectChangeHandle"
        :onSyncTableData="syncTableFun"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls">
          <multiuse-button size="small" type="primary" :click="batchAssign">下发</multiuse-button>
          <multiuse-button size="small" type="primary" :click="exportHandler">导 出</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <!--&lt;!&ndash; 经销商查询 &ndash;&gt;-->
    <!--<BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">-->
      <!--<OwnerSearch :rowData="formData" :isSingleSelect = "false" @close="emitCloseHandler" />-->
    <!--</BaseDialog>-->
    <Drawer :visible.sync="visible" title="对账单信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Detail :rowData="detailFormData" @close="emitCloseHandler1" />
    </Drawer>
  </div>
</template>
<script>
import moment from 'moment';
import { exportExcelFile } from '@/utils/index';
import { dictionary } from '@/utils/dictMixin';
import { queryList,exportExcel,batchAssign} from '@/api/omFinanceP/MoneyManage/FundBalanceStatement';
import { getRegion, getCommunity, getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index'; //事业部，办事处
import { dealerCommon, DICT_CODE } from '@/api/cms-api/origin/commonDealerType'; //经销商类型工具类
import { region } from '@/api/cms-common/region'; //行政区域
// import OwnerSearch from '../AccountDetailsQuery/ownerSeacher';
import Detail from './detail';

export default {
  name: 'FundBalanceStatement',
  mixins: [dictionary, region, dealerCommon],

  data() {
    this.BaseTable = null;
    return {
      ORG_TYPE_MARKETING_WAR_AREA: 15061015, // 营销战区
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {
      },
      formData: {},
      detailFormData: {},
      cellstyles: [],
      isDealer: false,
      visible: false,
      exportLoading: false,
      selectRow: []
    };
  },
  components: {
    Detail
  },
  mounted() {
    this.initProvince();
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA, 'areaId');
  },
  created() {
  },
  methods: {
    // 状态为 21501002,21501003 禁止选择
    syncTableFun(data) {
      const disabledRow = data.filter(item => (item.state === 21501002 || item.state === 21501003));
      this.$refs.table.SET_DISABLE_SELECT(disabledRow);
    },
    // 选择row
    selectChangeHandle(row) {
      this.selectRow = row;
    },
    // 下发
    batchAssign() {
      if (this.selectRow.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择要下发的数据'
        });
      } else {
        this.$confirm('是否要下发', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const res = await batchAssign(this.selectRow);
            if (res.resultCode == 200) {
              this.$message({
                type: 'success',
                message: '下发成功'
              });
              this.fetchParams = { ...this.fetchParams}
            } else {
              this.$message({
                type: 'error',
                message: res.errMsg
              });
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
      }
    },
    // 导出
    async exportHandler() {
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true;
          exportExcel(this.fetchParams)
            .then(response => {
              exportExcelFile(response.data, '资金对账信息');
              this.exportLoading = false;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },

    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // seacherFun() {
    //   this.isDealer = true;
    // },
    emitCloseHandler1() {
      this.visible = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      this.visible = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.topFilterList.find(x => x.fieldName == 'dealerCodes').initialValue = dealerCodes.toString();
      }
    },
    //获取顶层组织数据
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === filedName).itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find((item) => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
    },
    addHandle() {
      this.isAdd = true;
    },
    detailHandle(row) {
      this.detailFormData = row;
      this.visible = true;
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [], change: (props) => this.initCity(props) },
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [] },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '输入多个经销商代码时，请用英文逗号隔开',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'RANGE_DATE',
          label: '年月',
          fieldName: 'startDate|endDate',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'monthrange',
          valueFormat: 'yyyy-MM'
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'state',
          placeholder: '请选择',
          itemList: this.createDictList('2150')
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 50,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '状态',
          dataIndex: 'state',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2150'),
          render: props => {
            return <span>{this.createDictText(props.row.state, '2150')}</span>;
          }
        },
        {
          title: '对账分类',
          dataIndex: 'type',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2151'),
          render: props => {
            return <span>{this.createDictText(props.row.type, '2151')}</span>;
          }
        },
        {
          title: '年月',
          dataIndex: 'reconciliationDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '整车款自有资金余额（DMS）',
          dataIndex: 'ownBalanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: false,
          precision: 2,
          numberFormat: true
        },
        {
          title: '整车款三方资金余额（DMS）',
          dataIndex: 'threeBalanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: false,
          precision: 2,
          numberFormat: true
        },
        {
          title: '整车款自有资金余额（SAP）',
          dataIndex: 'sapOwnBalanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: false,
          precision: 2,
          numberFormat: true
        },
        {
          title: '整车款三方资金余额（SAP）',
          dataIndex: 'sapThreeOwnBalanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: false,
          precision: 2,
          numberFormat: true
        },
        {
          title: '整车返利余额（DMS）',
          dataIndex: 'rebateBalanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: false,
          precision: 2,
          numberFormat: true
        },
        {
          title: '整车返利余额（SAP）',
          dataIndex: 'sapRebateBalanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: false,
          precision: 2,
          numberFormat: true
        },
        {
          title: '下发人',
          dataIndex: 'issueBy',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '下发日期',
          dataIndex: 'issueDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '确认人',
          dataIndex: 'confirmBy',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '确认日期',
          dataIndex: 'confirmDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
      ];
    }
  }
};
</script>
